package me.youline.dataServer.service.socialAction;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import me.youline.dataServer.service.socialAction.event.SocialActionEvent;
import me.youline.dataServer.service.socialAction.listener.SocialActionEventListener;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 该发布器具备多线程处理的能力，它拥有一个核心线程数为3，最大线程数为5的线程池。每一个事件的处理可以在单独的线程执行。以避免对外部的影响。
 * @author linhan
 */
@Component
public class DefaultSocialActionEventPublisher implements SocialActionEventPublisher{
	
	private Executor threadPool = new ThreadPoolExecutor(3, 5, 15, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>(30),new RejectedExecutionHandler() {
		
		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
			
			}
			executor.submit(r);
			
		}
	});
	
	@Autowired
	private SocialActionEventListener listener;
	
	@Override
	public void publishSocialEvent(final SocialActionEvent event) {
		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				listener.handleEvent(event);
			}
		}); 
	}

}
